/**
 * @ author: 汪孟苹
 */
define(["jquery", "bbcare", "fu/app/comm/validate", "fu/app/comm/attention", "oms_config/root",
	"scprit/followup/app/patientManager/addPatient.servers.js",
	"scprit/followup/app/patientManager/addPatient.ui.js",
	"scprit/followup/app/question/question.ui.js",
	"scprit/followup/app/question/question.servers.js",
	"scprit/followup/app/question/question.event.js"
], function ($, $bb, $validate, $attention, $root, $addPatientServers, $addPatientUi, $questionUi, $questionServers, $questionEvent) {
	var event = {}

	var URL = $bb.baseUrl("followup")
	let followQueueId = ""
	let questiones = null
	let patientInfo = null
	let curInfoStatus = ""
	let questionParams = null
	let questionVal = null
	/**
	 * 点击关闭，跳转到工作站
	 */
	var onCloseSelect = function () {
		var config = $root.init()
		var pageParams = $bb.getPageParams()
		$bb.selectNavbar(config.route.addPatientClose)
	}
	event.onCloseSelect = function () {
		onCloseSelect()
	}
	/**
	 * 根据患者基本信息跳转到门诊录入页面
	 */
	var getPatientInfoCallback = function (data) {
		var imgSrc = 'page/followup/imgs/comm/' + (data.PatientInfo.gender == 'F' ? 'girl' : 'boy') + '.png'
		var params = {
			patientSchemeId: data.QueueSchemeInfo.ptSchemeId,
			followQueueId: data.QueueSchemeInfo.queueId,
			patientName: data.PatientInfo.userName,
			imgSrc: imgSrc,
			queuename: data.QueueSchemeInfo.queueName,
			patientId: data.PatientInfo.id,
		}
		var config = $root.init()
		$bb.openPage(config.route.addPatientJump, params)
	}
	/**
	 * 保存成功后的回调函数
	 */
	var getSaveBuildCallback = function (data) {
		var pageParams = $bb.getPageParams()
		// $addPatientServers.bindHisIdAndPatientId(data, pageParams.pat1, function () {
		// 	$bb.toastShow("添加成功！", 2000)
		// 	$addPatientServers.ajaxPatientInfo(data, getPatientInfoCallback)
		// })
		$bb.toastShow("添加成功！", 2000)
		$addPatientServers.ajaxPatientInfo(data, getPatientInfoCallback)
	}
	/**
	 * 点击保存按钮
	 */
	var onSaveClick = function (params) {
		var patientName = $("#questionDetail form").find("input[name='Pub1100002']").val()
		var formId = $("#questionDetail form").attr("id")
		var questiones = $questionServers.getDataForDom(formId)
		$addPatientServers.ajaxSaveBuildQuestions(params, patientName, questiones, getSaveBuildCallback)
	}
	/**
	 * 表单提交前的校验
	 */
	var onValidateClick = function () {
		var params = $(this).data("params")
		if ($validate.init()) {
			onSaveClick(params)
		}
	}
	let ajaxQueryFamilyInfoCallback = function (data) {

		var formId = $("#questionDetail form").attr("id")
		var value = $questionServers.getDataForDom(formId)

		let newVal = { ...value, ...questionVal, ...data.values }
		if (data) {
			if (Object.keys(data.values).length > 0) {

				$questionUi.init({
					id: "questionDetail",
					list: questiones,
					showIcon: true,
					values: newVal,
					initParams: {
						queueId: followQueueId
					}
				})
			}
			$questionEvent.init({
				"getPatientsByPhone": {
					params: questionParams,
					callback: buildQuestions
				},
				"getGeneFusion": {
					"followQueueId": questionParams.queueId,
					"values": newVal
				}
			})
			$attention.init()
			$validate.blurInit()
		}
	}
	/**
	 * 母亲手机号查询既往数据
	 */
	$('.content-main').on('blur', 'input[name=Pub1100001]', function () {
		console.log($(this).val())
		console.log('followQueueId', followQueueId)
		let phone = $(this).val()
		if (phone) {
			$addPatientServers.ajaxQueryFamilyInfo(followQueueId, phone, ajaxQueryFamilyInfoCallback)
		}

	})
	/**
	 * 建档问卷请求成功会后的回调函数
	 */
	var getBuildQuestCallback = function (data, params, values) {
		followQueueId = params.queueId
		questiones = data.questiones
		questionParams = params

		questionVal = values
		$questionUi.init({
			id: "questionDetail",
			list: data.questiones,
			showIcon: true,
			values: values,
			initParams: {
				queueId: params.queueId
			}
		})

		$questionEvent.init({
			"getPatientsByPhone": {
				params: params,
				callback: buildQuestions
			},
			"getGeneFusion": {
				"followQueueId": params.queueId,
				"values": values
			}
		})
		$attention.init()
		$('.validatebox').data("attentionFun", $attention.blurInit)	// 校验之前提示警告
		$validate.blurInit()
		var config = $root.init()
		var topbars = [
			{
				"icon": "fa fa-floppy-o",
				"name": "保存",
				"callback": onValidateClick,
				"params": params
			}
		]
		if (config.dom.addPatientClose) {
			topbars.push({
				"icon": "fa fa-times",
				"name": "关闭",
				"callback": onCloseSelect,
			})
		}
		if (window.__config__.role.indexOf('ReadOnly') == -1) {
			$bb.toolbar(topbars)
		}

	}
	/**
	 * 建档问卷
	 */
	var buildQuestions = function (params, result) {
		$addPatientServers.ajaxBuildQuestions(params, getBuildQuestCallback, result.values)
	}
	/**
	 * 建档问卷
	 */
	var bookbuilding = function (params) {
		$addPatientUi.tit({
			id: "queueName",
			queueName: params.queueName
		})
		buildQuestions(params, { "values": null })
	}
	/**
	 * 点击队列card
	 */
	event.onQueueNavSelect = function () {
		$(this).addClass("active").siblings().removeClass("active")
		var queueName = $(this).find(".queue-name").text()
		var queueId = $(this).attr("queueId")
		var schemeId = $(this).attr("schemeId")
		var params = {
			"queueName": queueName,
			"queueId": queueId,
			"schemeId": schemeId
		}
		bookbuilding(params)
	}

	/**
	 * 渲染 His 系统过来的数据
	 * @param { object } params
	 */
	event.is_render = false
	event.renderHisData = function (params) {
		for (var i = 0; i < $('.queue-card').length; i++) {
			var dom = $('.queue-card')[i]
			if ($(dom).attr('queueid') == params.queueid) {
				$(dom).click()
			}
		}
		// 渲染数据
		function renderDataToDom () {
			setTimeout(function () {
				if ($('input[name=Pub1100001]')) {
					renderData(params)
				} else {
					renderDataToDom()
				}
			}, 1000)
		}
		renderDataToDom()
	}

	function renderData (params) {
		// console.log('params1',params)
		// 姓名
		$('input[name=Pub1100002]').val(params.pAT_NAME)
		// 性别
		if (params.hasOwnProperty('pHYSI_SEX_NAME') && params.pHYSI_SEX_NAME == '男') {
			$('.radio-inline')[0].click()
		} else {
			$('.radio-inline')[1].click()
		}
		// 出生日期
		$('input[name=Pub1100004]').val(params.dATE_BIRTH)
		// 住院号
		$('input[name=Pub12x00008]').val(params.iNHOSP_NO)
		// 家庭住址
		$('input[name=jd_jtzz]').val(params.cURR_ADDR)

		// 出生体重
		$('input[name="jd_cstz"]').val(params.bIRTH_WEIGHT)
		$('input[name="jd_cssc"]').val(params.bIRTH_HEIGHT)
		$('input[name="jd_cstw"]').val(params.bIRTH_HEAD)

		event.is_render = true
	}



	/**
	 * 自动计算住院天数
	 */
	$('.content-main').on('blur', 'input[name=zcejd_ruyrq]', function () {
		computeDays()
	})
	$('.content-main').on('blur', 'input[name=Pub13x00010]', function () {
		computeDays()
	})
	function computeDays () {
		var enterDate = $('input[name=zcejd_ruyrq]').val()
		var outDate = $('input[name=Pub13x00010]').val()
		if (!enterDate || !outDate) return
		enterDate = new Date(enterDate).getTime()
		outDate = new Date(outDate).getTime()
		var reduce = Math.floor(outDate / 1000) - Math.floor(enterDate / 1000)
		var oneDay = 3600 * 24
		var day = Math.ceil(reduce / oneDay)
		$('input[name=zcejd_zyts]').val(day)
	}

	/**
	 * 自动计算体重增长
	 */
	$('.content-main').on('blur', 'input[name=zcejd_cstz]', function () {
		computeWeight()
		getPValue('00001', $('input[name=zcejd_cstz]').val(), 0, 'zcejd_tzpz')
	})
	$('.content-main').on('blur', 'input[name=zcejd_cytz]', function () {
		computeWeight()
		getPValue('00001', $('input[name=zcejd_cytz]').val(), getDiffDays(), 'zcejd_cytzpz')
	})
	function computeWeight () {
		var before = $('input[name=zcejd_cstz]').val()
		var after = $('input[name=zcejd_cytz]').val()
		var val = after - before
		$('input[name=zcejd_cytzzz]').val(val)
	}

	/**
	 * 获取出生身长
	 */
	$('.content-main').on('blur', 'input[name=zcejd_cssc]', function () {
		getPValue('00002', $('input[name=zcejd_cssc]').val(), 0, 'zcejd_scpz')
	})

	/**
	 * 获取出生头围
	 */
	$('.content-main').on('blur', 'input[name=zcejd_cstw]', function () {
		getPValue('00003', $('input[name=zcejd_cstw]').val(), 0, 'zcejd_twpz')
	})

	/**
	 * 获取出院身长
	 */
	$('.content-main').on('blur', 'input[name=zcejd_cysc]', function () {
		getPValue('00002', $('input[name=zcejd_cysc]').val(), getDiffDays(), 'zcejd_cyscpz')
	})

	/**
	 * 获取出院头围
	 */
	$('.content-main').on('blur', 'input[name=zcejd_cytw]', function () {
		getPValue('00003', $('input[name=zcejd_cytw]').val(), getDiffDays(), 'zcejd_cytwpz')
	})

	/**
	 * 获取出生时的 p 值
	 * @param { string } type
	 * @param { string } val
	 */
	function getPValue (type, val, age, target) {
		var gender = $('input[name=Pub1100003]:checked').val()
		var pweek = $($('select[name=Pub1100006]')[0]).val()
		var pday = $($('select[name=Pub1100006]')[1]).val()

		if (!type || !val || !gender) return
		if (age != 0 && !age) return
		gender = gender == '男' ? "N" : "F"
		$bb.ajax({
			url: URL + 'followup/service/patient/growth/getPercentiles',
			data: JSON.stringify({
				data:
				{
					type: type,
					gender: gender,
					age: age,
					value: val,
					pweek: pweek,
					pday: pday
				}
			}),
			success: function (res) {
				// if (res.data.percentiles == '<3%') {
				// 	$(`select[name=${target}]`).val('<P3')
				// } else if (res.data.percentiles == '>97%') {
				// 	$(`select[name=${target}]`).val('>P97')
				// } else {
				// 	$(`select[name=${target}]`).val('P3～P97')
				// }
				$(`select[name=${target}]`).val(res.data.percentiles)
			}
		})
	}

	function getDiffDays () {
		var birth = $('input[name=Pub1100004]').val()
		var target = $('input[name=Pub13x00010]').val()
		if (!birth || !target) return 0
		birth = Math.floor(new Date(birth).getTime() / 1000)
		target = Math.floor(new Date(target).getTime() / 1000)
		var day = 3600 * 24
		var reduce = Math.ceil((target - birth) / day)
		console.log(reduce)
		return reduce
	}

	return event
})
